package chapter.fifth.item23;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import chapter.fourth.item20.Circle;
import chapter.fourth.item20.Rectangle;

/**
 * 拒绝原生态类型
 * @author lzy
 *
 */
public class rejectRawType {
	
	private static final Set stamps1 = new HashSet();
	
	private static final Collection<Circle> stamps2 = new HashSet();
	
	//原生态类型，运行时强转报错
	static void test1(){
		stamps1.add(new Circle(1));
		for(Iterator i=stamps1.iterator();i.hasNext();){
			Rectangle re = (Rectangle)i.next();
		}
	}
	
	//使用参数化类型，编译时检查类型约束
	static void test2(){
		//编译不通过
		//The method add(Circle) in the type Collection<Circle> is not applicable for the arguments (Rectangle)
		//stamps2.add(new Rectangle(1d,2d));
	}
	
	//原生态类型，运行时强转报错
	static void test3(){
		List<String> ss = new ArrayList<String>();
		unsafeAdd(ss,new Integer(2));
		String s = ss.get(0);
	}

	private static void unsafeAdd(List ss, Object o) {
		ss.add(o);
	}
	
	//无限制的通配符类型
	static int test4(Set<?> s1,Set<?> s2){
		int result = 0;
		for(Object o1:s1)
			if(s2.contains(o1))
				result ++;
		return result;
	}
	
	//instanceof不允许参数化类型使用,可以用原生类型代替
	static void test5(Object o){
		if(o instanceof Set<?>){
			Set<?> m = (Set<?>) o;
		}
	}

	public static void main(String[] args) {
		//抛出类型转换异常 Circle cannot be cast to Rectangle
		//test1();
		
		//抛出类型转换异常 java.lang.Integer cannot be cast to java.lang.String
		//test3();
		
		//无限制通配符类型，无法添加除了null之外任何元素
		String[] x1 = {"sd","djf"};
		Set<?> s1 = new HashSet(Arrays.asList(x1));
		String[] x2 = {"sd","djff"};
		Set<?> s2 = new HashSet(Arrays.asList(x2));
		int sum = test4(s1,s2);
		System.out.println(sum);
		
	}
}
